package com.qf.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局解决中文乱码的过滤器
 *      post提交中文乱码
 *      响应的中文乱码
 */
@WebFilter("/*") //过滤所有
public class GlobalCharacterFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("全局过滤器初始化了");
    }

    public void destroy() {
        System.out.println("全局过滤器销毁");
    }

    //过滤任务
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        //将ServletRequest/ServletResponse 强转HttpServletRequest/HttpServletResponse
        HttpServletRequest request  = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;


        //request获取前端的提交方式
        String method = request.getMethod();
        if("POST".equals(method)){
            //post提交,解决post提交的中文乱码
            request.setCharacterEncoding("utf-8") ;
        }

        //解决响应的中文乱码
        response.setContentType("text/html;charset=utf-8");

        //放行
        chain.doFilter(request,response);


    }
}
